import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_SCREENLOCKED } from '@/store/mutation-types';

import { getUserInfo as getUserInfoApi, login } from '@/api/system/user';
import { storage } from '@/utils/Storage';

// JWT解析函数
function parseJwt(token: string) {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(function (c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        })
        .join('')
    );
    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error('JWT解析失败:', error);
    return null;
  }
}

export type UserInfoType = {
  // TODO: add your own data
  username: string;
  pcs: string;
};

export interface IUserState {
  token: string;
  username: string;
  pcs: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: UserInfoType;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    username: '',
    pcs: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPcs(): string {
      return this.pcs;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },
    // 登录
    async login(params: any) {
      try {
        const response = await login(params);
        const { access_token } = response as any;

        // 解析jwt获取用户信息数据
        const jwtData = parseJwt(access_token);
        console.log('🚀 ~ login ~ JWT解析数据:', jwtData);

        if (jwtData) {
          const userInfo: UserInfoType = {
            username: jwtData.username || jwtData.sub || '',
            pcs: jwtData.pcs || '',
          };

          // 从JWT的exp字段获取过期时间（秒）
          const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
          const exp = jwtData.exp ? Math.max(0, jwtData.exp - now) : 7 * 24 * 60 * 60; // 如果没有exp，默认7天

          storage.set(ACCESS_TOKEN, access_token, exp);
          storage.set(CURRENT_USER, userInfo, exp);
          storage.set(IS_SCREENLOCKED, false);

          this.setToken(access_token);
          this.setUserInfo(userInfo);
        }

        return response;
      } catch (error) {
        console.log('🚀 ~ login ~ error:', error);
        throw error;
      }
    },

    // 获取用户信息
    async getInfo() {
      const data = await getUserInfoApi();
      data.permissions = [data.role];
      const permissionsList = [data.role];
      this.setPermissions(permissionsList);
      const userinfo: UserInfoType = {
        username: data.username,
        pcs: data.pcs,
      };
      this.setUserInfo(userinfo);
      return data;
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo({ username: '', pcs: '' });
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
    },
  },
});

// Need to be used outside the setup
export function useUser() {
  return useUserStore(store);
}
